package test.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Scanner;

public class MQProducer {

    private static final String QUEUE_NAME = "hello";

    public void start(){
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = null;
        Channel channel = null;
        Scanner sc = new Scanner(System.in);
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            String message = "hello world,try again";
            System.err.println("-----输入字符串，回车进行发送，\"quit\"退出-------");
            while (sc.hasNext()){
                message = sc.nextLine();
                channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
                System.out.println("[x] Sent'"+message+"'");
                if(message.equals("quit")){
                    message = "Producer已经退出！！";
                    System.out.println("[x]Sent'"+message+"'");
                    channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
                    break;

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {
        MQProducer p = new MQProducer();
        p.start();
    }
}

